<template>
  <div class="YoudaoTranslate" id="YoudaoTranslate">
    <el-form id="youdao_trans_from" ref="form" :model="form_input" label-width="80px" @submit.native.prevent>
      <el-input id="youdao" v-model="form_input.input" @keyup.enter.native="enter_press()"></el-input>
      <el-form-item>
      </el-form-item>
      <el-button type="primary" @click="youdaoTranslate('ZH_CN2EN')">中译英</el-button>
      <el-button type="primary" @click="youdaoTranslate('EN2ZH_CN')">英译中</el-button>
      <el-button type="primary" @click="youdaoTranslate('ZH_CN2JA')">中译日</el-button>
      <el-button type="primary" @click="youdaoTranslate('JA2ZH_CN')">日译中</el-button>
    </el-form>

    <el-form ref="form" :model="form_output" label-width="80px">
      <el-form-item>
      </el-form-item>
      <el-input type='textarea' rows="8" cols="80" v-model="form_output.output"></el-input>
    </el-form>
  </div>
</template>

<script>
  import $ from 'jquery'
  export default {
    name: 'YoudaoTranslate',
    data() {
      return {
        form_input: {
          input: ''
        },
        form_output: {
          output: ''
        },
        error_message: '请输入有效信息!!!',
        url: 'http://fanyi.youdao.com/translate?&doctype=json&type={type}&i={source}'
      }
    },
    methods: {
      youdaoTranslate(type) {
        let source = this.form_input.input;
        let targetUrl = this.url.format({
          'type': type,
          'source': source
        })
        let array = new Array();
        this.$axios.get(targetUrl).then(response => {
          try {
            let result = response.data
            let code = result['errorCode']
            if (code == 0) {
              let resultArr = result['translateResult'];
              if (resultArr.length >= 1) {
                for (let i = 0; i < resultArr[0].length; i++) {
                  array.push(resultArr[0][i]['tgt'])
                }
              } else {
                array.push(result)
              }
            } else {
              array.push(result)
            }
          } catch (err) {
            array = new Array();
            array.push('翻译出故障啦!!!!!!!!!!!!!!!!!!!!\n' + response.data)
          }
          this.form_output.output = array.join('\n')
        });
      },
      enter_press(){
        let input = this.form_input.input;
        if(/^\w+/.test(input)){
          this.youdaoTranslate('EN2ZH_CN');
        }else{
          this.youdaoTranslate('ZH_CN2EN');
        }
      }
    }
  }
</script>

<style scoped>

</style>
